package com.lty.spider.pipeline;

import com.lty.spider.entity.Movie;
import com.lty.spider.entity.MovieDo;
import com.lty.spider.util.DbUtil;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

/**
 * create by  lty
 * on  2019-06-14  13:45
 */
public class MoivePipeline implements Pipeline {
    @Override
    public void process(ResultItems resultItems, Task task) {
        Map<String, Object> all = resultItems.getAll();
       Movie  movie = (Movie) all.get("movie");
        List<String> titleList = movie.getTitle();
        List<String> contentList  = movie.getContent();
        List<String> linkList  = movie.getLink();
        MovieDo movieDo = new MovieDo();

        String sql="insert into movie(title,content,link) values (?,?,?)";

        DbUtil dbUtil = new DbUtil();
        Connection connection = dbUtil.getConnection();
        PreparedStatement statement =null;
        try {
            statement = connection.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }


        for (int i = 0; i < titleList.size(); i++) {
            movieDo.setName(titleList.get(i));
            movieDo.setLink(linkList.get(i));
            movieDo.setContent(contentList.get(i));
            try {
                statement.setString(1,titleList.get(i));
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                statement.setString(2,contentList.get(i) );
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                statement.setString(3, linkList.get(i));
            } catch (SQLException e) {
                e.printStackTrace();
            }
/*            System.out.println(movieDo.getName());
            System.out.println(movieDo.getLink());
            System.out.println(movieDo.getContent());*/
            try {
                int i1 = statement.executeUpdate();
                System.out.println("插入返回值"+ i1);
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }


    }
}
